package com.fenrirtec.aepp.common.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dao.SystemDao;
import com.fenrirtec.core.database.DatabaseSessionManager;
import com.fenrirtec.core.exception.DatabaseException;

public class SystemDao_JDBCImpl implements SystemDao {

	private static final Logger logger = LoggerFactory.getLogger(SystemDao_JDBCImpl.class);

	@Override
	public String generateRandom(int size) {
		if (logger.isInfoEnabled()) {
			logger.info("[SystemDao_JDBCImpl#generateRandom] start.");
		}

		PreparedStatement statement = null;
		
		try {
			String sql = "select get_random(?) as random";
			
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemDao_JDBCImpl#generateRandom] sql={}", sql);
			}
			
			Connection connection = DatabaseSessionManager.getInstance().getSession();
			statement = connection.prepareStatement(sql);
			statement.setInt(1, size);
			ResultSet resultSet = statement.executeQuery();
			
			if (resultSet.next()) {
				return resultSet.getString("random");
			}
			
			return null;
			
		} catch (SQLException e) {
			if (logger.isTraceEnabled()) {
				logger.trace("[SystemDao_JDBCImpl#generateRandom] sql error occurred.", e);
			}
			throw new DatabaseException("database error occurred.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[SystemDao_JDBCImpl#generateRandom] finish.");
			}
			if (statement != null) { try { statement.close(); } catch (SQLException e) {} }
		}
	}
}
